﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hr.IDAL;
using Hr.Model;
using System.Data.Entity;
using System.Data.Entity.Migrations;

namespace Hr.DAL
{
    public class RoleDAL : BaseDAL<Role_Name>, IRole_NameDAL
    {
        // 创建EF对象
        private DbContext db = DbContextFactory.Create();
        #region 获取数据

        /// <summary>
        /// 获取所有角色信息，根据权限值排序
        /// </summary>
        /// <returns></returns>
        public List<Role_Name> GetRoleNameAll()
        {
            return db.Set<Role_Name>().OrderByDescending(n => n.PowerValue).ToList();
        }

        /// <summary>
        /// 根据角色ID，获取角色信息
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns>角色信息</returns>
        /// <author>乐涛</author>
        /// <create>2020/8/7</create>
        /// <update>null</update>
        public Role_Name GetRoleName(int id)
        {
            return db.Set<Role_Name>().SingleOrDefault(n => n.pk_Name == id);
        }

        /// <summary>
        /// 根据角色名称进行模糊查询
        /// </summary>
        /// <param name="RoleName_CHS"></param>
        /// <returns></returns>
        public List<Role_Name> SelRoleName(string RoleName_CHS)
        {
            return db.Set<Role_Name>().Where(n => n.RoleName_CHS.Contains(RoleName_CHS)).ToList();
        }


        /// <summary>
        /// 获取所有页面菜单数据，递归获取菜单，默认一级parentID为0表示最高级
        /// </summary>
        /// <param name="parentID"></param>
        /// <returns></returns>
        public List<object> GetMenuSlid(int parentID)
        {
            List<object> lst = new List<object>();
            foreach (Sys_Menu item in db.Set<Sys_Menu>().Where(n => n.ParentID == parentID))
            {
                List<object> ChildrenSys = new List<object>();
                if (db.Set<Sys_Menu>().Where(n => n.ParentID == item.pk_Menu).Count() > 0)
                {
                    //递归
                    ChildrenSys = GetMenuSlid(item.pk_Menu);
                }
                Dictionary<string, object> dt = new Dictionary<string, object>()
                {
                    {"dt",item},
                    {"children",ChildrenSys }
                };
                lst.Add(dt);
            }
            return lst;
        }

        /// <summary>
        /// 获取所有页面菜单数据，默认一级parentID为0表示最高级
        /// </summary>
        /// <param name="parentID"></param>
        /// <returns></returns>
        public IEnumerable<object> GetMenuList(int parentID)
        {
            return GetMenuPage(parentID).Select(n => new { n.pk_Menu, n.Name_CHS, n.ParentID, n.SortID, n.Url, n.TypeID, db.Set<Sys_TypeID>().Where(t => t.TableName.Equals("Sys_Menu") & t.ID == n.TypeID).FirstOrDefault().TypeName_CHS, db.Set<Sys_TypeID>().Where(t => t.TableName.Equals("Sys_Menu") & t.ID == n.TypeID).FirstOrDefault().Visual });
        }

        /// <summary>
        /// 通过角色ID获取所有开通权限的菜单ID集合
        /// </summary>
        /// <param name="fk_RoleName"></param>
        /// <returns></returns>
        public IQueryable<int?> GetRoleListCheck(int fk_RoleName)
        {
            return db.Set<Role_List>().Where(n => n.IsUse == true & n.fk_RoleName == fk_RoleName).Select(s => s.fk_Menu);
        }


        //获取页面集合并排序,本类访问
        private List<Sys_Menu> GetMenuPage(int parentID)
        {
            List<Sys_Menu> lst = new List<Sys_Menu>();
            foreach (Sys_Menu item in db.Set<Sys_Menu>().Where(n => n.ParentID == parentID).OrderBy(n => n.SortID))
            {
                lst.Add(item);
                List<Sys_Menu> ChildrenSys = new List<Sys_Menu>();
                if (db.Set<Sys_Menu>().Where(n => n.ParentID == item.pk_Menu).Count() > 0)
                {
                    //递归
                    ChildrenSys = GetMenuPage(item.pk_Menu).OrderBy(n => n.SortID).ToList();
                    lst.AddRange(ChildrenSys);
                }
            }
            return lst;
        }
        #endregion


        #region 添加、修改

        /// <summary>
        /// 编辑、添加角色信息
        /// </summary>
        /// <param name="r">角色信息</param>
        /// <param name="type">类型（Add或者Edit）</param>
        public void UpdateRoleName(Role_Name r,string type)
        {
            if (type.Equals("Add"))
            {
                //添加
                db.Set<Role_Name>().Add(r);
            }
            else if (type.Equals("Edit"))
            {
                //更新
                //Role_Name Rn = db.Set<Role_Name>().SingleOrDefault(n => n.pk_Name == r.pk_Name);
                //Rn.RoleName_CHS = r.RoleName_CHS;
                //Rn.PowerValue = r.PowerValue;
                //Rn.RoleName_CHT = r.RoleName_CHT;
                //Rn.RoleName_EN = r.RoleName_EN;
                //db.Set<Role_Name>().Add(Rn);
                db.Set<Role_Name>().AddOrUpdate(r);
            }
        }

        /// <summary>
        /// 根据角色ID修改其绑定页面是否开启权限
        /// </summary>
        /// <param name="fk_RoleName"></param>
        /// <param name="CheckDt"></param>
        public void UpdateRoleCheck(int fk_RoleName, List<int> CheckDt)
        {
            List<Role_List> RoleList = new List<Role_List>();
            //先判断是否存在
            foreach (int item in CheckDt)
            {
                if (db.Set<Role_List>().Where(n => n.fk_Menu == item & n.fk_RoleName == fk_RoleName).FirstOrDefault() == null)
                {
                    Role_List rl = new Role_List();
                    //不存在则创建
                    rl.fk_Menu = item;
                    rl.fk_RoleName = fk_RoleName;
                    rl.IsUse = false;
                    rl.IsAdmin = false;
                    rl.PowerList = "";
                    rl.fk_Company = 0;
                    db.Set<Role_List>().Add(rl);
                }
            }
            //保存
            db.SaveChanges();
            //查询并且修改
            foreach (Role_List r in db.Set<Role_List>().Where(n => n.fk_RoleName == fk_RoleName))
            {
                if (CheckDt.Contains(int.Parse(r.fk_Menu.ToString())))
                {
                    r.IsUse = true;
                }
                else
                {
                    r.IsUse = false;
                }
            }
        }
        #endregion


        #region 删除
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="r"></param>
        public void DelRoleName(Role_Name r)
        {
            //获取权限最高的角色
            Role_Name TopRn= db.Set<Role_Name>().OrderByDescending(n => n.PowerValue).FirstOrDefault();
            //查询角色下的所有用户
            List<User_List> uList = db.Set<User_List>().Where(n => n.RoleValue == r.pk_Name).ToList();
            //将该角色下的所有用户转给权限最高的角色
            foreach (User_List item in uList)
            {
                item.RoleValue = TopRn.pk_Name;
                item.RoleList = TopRn.pk_Name.ToString();
            }
            //清空角色菜单表下所绑定的数据
            List<Role_List> RoleList = db.Set<Role_List>().Where(n => n.fk_RoleName == r.pk_Name).ToList();
            db.Set<Role_List>().RemoveRange(RoleList);
            //删除角色
            db.Set<Role_Name>().Remove(r);
        }

        #endregion

        //实现接口成员
        public bool SaveChanges()
        {
            return db.SaveChanges() > 0;
        }
    }
}
